import time
from datetime import timedelta, datetime
from flask import current_app
from flask import redirect, g
from flask import request, jsonify
from flask import session
from flask import url_for

from info.models import User
from info.utils.response_code import RET
from . import admin_blue
from flask import render_template
from info.utils.commons import user_login_data


@admin_blue.route('/index')
@user_login_data
def index():
    user = g.user
    data = {
        'user_info': user.to_dict() if user else None
    }
    return render_template('admin/index.html', data=data)


@admin_blue.route('/user', methods=['POST', 'GET'])
@user_login_data
def login():
    """
    管理员登陆
    1. 如果是get请求返回admin.login页面，post请求返回admin.index页面
    :return:
    """
    user = g.user
    if request.method == 'GET':
        is_admin = session.get('is_admin', False)
        data = {
            'user_info': user.to_dict() if user else None
        }
        if is_admin:
            return render_template('admin/index.html', data=data)
        return render_template('admin/login.html')
    mobile = request.form.get('username')
    password = request.form.get('password')
    print(mobile, '  ', password)
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

    try:
        user = User.query.filter(User.mobile == mobile, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询管理员信息失败')
    # if not user:
    #     return jsonify(errno=RET.DATAERR, errmsg='无此管理员')

    if not user.check_password(password) or not user:
        return jsonify(errno=RET.DATAERR, errmsg='账号或密码输入错误')

    session['admin_mobile'] = mobile
    session['admin_id'] = user.id
    return redirect(url_for('admin_blue.index'))
    # return render_template('admin/index.html')


@admin_blue.route('/user_count')
def user_count():
    """
    用户统计
    :return:
    """
    # 总用户数
    # total_user = 0
    try:
        total_user = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='总人数查询失败')
    # if not total_user:
    #     return jsonify(errno=RET.DATAERR, errmsg='无用户数据')

    # 月新增用户
    # time.strptime(string, format)将字符串日期装为日期格式的数据
    current_time = time.localtime()
    month_begin_str = '%d-%02d-%02d' % (current_time.tm_year, current_time.tm_mon, 1)
    month_begin = datetime.strptime(month_begin_str, '%Y-%m-%d')
    # addMonth_user = 0
    try:
        addMonth_user = User.query.filter(User.is_admin==False, User.create_time>=month_begin).count()
        # addMonth_user = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='月新增加用户数查询失败')
    # if not addMonth_user:
    #     return jsonify(errno=RET.DATAERR, errmsg='无新增用户数据')

    # 日新增用户
    day_begin_str = '%d-%02d-%02d' % (current_time.tm_year, current_time.tm_mon, current_time.tm_mday)
    day_begin = datetime.strptime(day_begin_str, '%Y-%m-%d')
    # addDay_user = 0
    try:
        addDay_user = User.query.filter(User.is_admin==False,  User.create_time>=day_begin).count()
        # addDay_user = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='月新增加用户数查询失败')
    # if not addDay_user:
    #     return jsonify(errno=RET.DATAERR, errmsg='无新增用户数据')

    """
    图表展示用户的活跃度
    1. 统计每隔1天d的在线人数
    2. 利用timedelta进行实现时间的前移
    """
    now_day = day_begin
    active_count = []
    active_time = []
    for day in range(0, 31):
        begin_day = now_day - timedelta(days=day)
        end_day = now_day - timedelta(days=day-1)
        # count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login>=begin_day, User.last_login<end_day).count()
            # count = User.query.filter(User.is_admin == False).count()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='活跃度查询失败')
        # if not count:
        #     return jsonify(errno=RET.DATAERR, errmsg='无活跃用户数据')
        begin_day_str = datetime.strftime(begin_day, '%Y-%m-%d')
        active_count.append(count)
        active_time.append(begin_day_str)
    active_time.reverse()
    active_count.reverse()

    print(active_time)
    print(active_count)

    data = {
        'total_user': total_user,
        'addMonth_user': addMonth_user,
        'addDay_user': addDay_user,
        'active_count': active_count,
        'active_time': active_time
    }
    return render_template('admin/user_count.html', data=data)


@admin_blue.route('/user_list')
def user_list():
    """
    用户列表
    :return:
    """
    return render_template('admin/user_list.html')

